import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author wujinhui
 * @title: Pool
 * @projectName untitled
 * @description: TODO
 * @date 2019/7/169:40
 */

public class Pool {
    // 存放要处理的线程
    private BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>();
    private final Set<Worker> workerSet = new HashSet<>();
    private static final int POOL_SIZE = 3;

    public Pool() {

        // 创建用于线程池中用于工作的线程
        for (int i = 0; i < POOL_SIZE; i++) {
            Worker worker = new Worker();
            worker.start();
            workerSet.add(worker);
        }
    }

    public void execute(Runnable runnable) {
        blockingQueue.add(runnable);
    }

    // 关闭线程池
    public void closePool() {
        while (!blockingQueue.isEmpty()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for(Worker worker : workerSet){
            worker.interrupt();
        }

    }

    class Worker extends Thread {
        Runnable runnable;

        // 从blockingQueue中取出线程并运行
        @Override
        public void run() {
            // 判断blockingQueue是否为空
            while (blockingQueue != null || blockingQueue.size() > 0) {
                try {
                    runnable = blockingQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (runnable != null) {
                    runnable.run();
                }

            }
        }
    }


    public static void main(String[] args) {
        Pool pool = new Pool();
        for (int i = 0; i < 6; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前线程为" + Thread.currentThread().getName());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            pool.execute(runnable);
        }
     //   pool.closePool();


    }
}


